package com.agrimall.servlet.admin;

import com.agrimall.entity.User;
import com.agrimall.service.UserService;
import com.agrimall.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.List;

/**
 * 管理员用户管理Servlet
 */
@WebServlet("/admin/user")
public class UserManageServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User admin = (User) session.getAttribute("admin");
        
        if (admin == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }
        
        String action = request.getParameter("action");
        
        if (action == null || action.equals("") || action.equals("list")) {
            // 用户列表
            listUsers(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User admin = (User) session.getAttribute("admin");
        
        if (admin == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }
        
        String action = request.getParameter("action");
        
        if (action != null && action.equals("updateStatus")) {
            // 更新用户状态
            updateUserStatus(request, response);
        } else if (action != null && action.equals("recharge")) {
            // 余额充值
            rechargeBalance(request, response);
        } else if (action != null && action.equals("batchDelete")) {
            // 批量删除用户
            batchDeleteUsers(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    /**
     * 用户列表
     */
    private void listUsers(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pageStr = request.getParameter("page");
        String userTypeStr = request.getParameter("userType");
        String keyword = request.getParameter("keyword");
        
        int page = 1;
        if (pageStr != null && !pageStr.isEmpty()) {
            try {
                page = Integer.parseInt(pageStr);
            } catch (NumberFormatException e) {
                page = 1;
            }
        }
        int pageSize = 10;
        
        List<User> users;
        int totalCount;
        
        // 判断是否有查询条件
        boolean hasConditions = (userTypeStr != null && !userTypeStr.trim().isEmpty()) ||
                               (keyword != null && !keyword.trim().isEmpty());
        
        if (hasConditions) {
            if (userTypeStr != null && !userTypeStr.trim().isEmpty() && 
                keyword != null && !keyword.trim().isEmpty()) {
                // 同时有类型和关键词
                Integer userType = Integer.parseInt(userTypeStr.trim());
                users = userService.searchUsersByTypeAndKeyword(userType, keyword.trim(), page, pageSize);
                totalCount = userService.countUsersByTypeAndKeyword(userType, keyword.trim());
            } else if (userTypeStr != null && !userTypeStr.trim().isEmpty()) {
                // 只有类型
                Integer userType = Integer.parseInt(userTypeStr.trim());
                users = userService.getUserListByType(userType, page, pageSize);
                totalCount = userService.countUsersByType(userType);
            } else {
                // 只有关键词
                users = userService.searchUsersByKeyword(keyword.trim(), page, pageSize);
                totalCount = userService.countUsersByKeyword(keyword.trim());
            }
        } else {
            users = userService.getUserList(page, pageSize);
            totalCount = userService.countAllUsers();
        }
        
        // 计算总页数
        int totalPages = totalCount > 0 ? (int) Math.ceil((double) totalCount / pageSize) : 1;
        
        request.setAttribute("users", users);
        request.setAttribute("page", page);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("userType", userTypeStr);
        request.setAttribute("keyword", keyword);
        
        request.getRequestDispatcher("/admin/user/list.jsp").forward(request, response);
    }
    
    /**
     * 更新用户状态
     */
    private void updateUserStatus(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String userIdStr = request.getParameter("userId");
            String statusStr = request.getParameter("status");
            
            if (userIdStr == null || userIdStr.trim().isEmpty() || 
                statusStr == null || statusStr.trim().isEmpty()) {
                out.print("{\"success\":false,\"message\":\"参数不完整\"}");
                return;
            }
            
            Long userId = Long.parseLong(userIdStr);
            Integer status = Integer.parseInt(statusStr);
            
            // 验证状态值
            if (status != 0 && status != 1) {
                out.print("{\"success\":false,\"message\":\"状态值无效\"}");
                return;
            }
            
            boolean success = userService.updateUserStatus(userId, status);
            if (success) {
                out.print("{\"success\":true,\"message\":\"操作成功\"}");
            } else {
                out.print("{\"success\":false,\"message\":\"操作失败，请重试\"}");
            }
        } catch (NumberFormatException e) {
            out.print("{\"success\":false,\"message\":\"参数格式错误\"}");
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\":false,\"message\":\"服务器错误：" + e.getMessage() + "\"}");
        } finally {
            out.flush();
            out.close();
        }
    }
    
    /**
     * 余额充值
     */
    private void rechargeBalance(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String userIdStr = request.getParameter("userId");
            String amountStr = request.getParameter("amount");
            
            if (userIdStr == null || userIdStr.trim().isEmpty() || 
                amountStr == null || amountStr.trim().isEmpty()) {
                out.print("{\"success\":false,\"message\":\"参数不完整\"}");
                return;
            }
            
            Long userId = Long.parseLong(userIdStr);
            BigDecimal amount = new BigDecimal(amountStr.trim());
            
            // 验证金额
            if (amount.compareTo(BigDecimal.ZERO) <= 0) {
                out.print("{\"success\":false,\"message\":\"充值金额必须大于0\"}");
                return;
            }
            
            boolean success = userService.rechargeBalance(userId, amount);
            if (success) {
                // 获取更新后的余额
                BigDecimal balance = userService.getUserBalance(userId);
                out.print("{\"success\":true,\"message\":\"充值成功\",\"balance\":\"" + balance + "\"}");
            } else {
                out.print("{\"success\":false,\"message\":\"充值失败，请重试\"}");
            }
        } catch (NumberFormatException e) {
            out.print("{\"success\":false,\"message\":\"参数格式错误\"}");
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\":false,\"message\":\"服务器错误：" + e.getMessage() + "\"}");
        } finally {
            out.flush();
            out.close();
        }
    }
    
    /**
     * 批量删除用户
     */
    private void batchDeleteUsers(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String[] userIdStrs = request.getParameterValues("userIds[]");
            
            if (userIdStrs == null || userIdStrs.length == 0) {
                out.print("{\"success\":false,\"message\":\"请选择要删除的用户\"}");
                return;
            }
            
            List<Long> userIds = new java.util.ArrayList<>();
            for (String userIdStr : userIdStrs) {
                try {
                    Long userId = Long.parseLong(userIdStr.trim());
                    userIds.add(userId);
                } catch (NumberFormatException e) {
                    // 忽略无效的ID
                }
            }
            
            if (userIds.isEmpty()) {
                out.print("{\"success\":false,\"message\":\"没有有效的用户ID\"}");
                return;
            }
            
            // 检查是否包含管理员用户
            for (Long userId : userIds) {
                User user = userService.getUserById(userId);
                if (user != null && user.getUserType() == 2) {
                    out.print("{\"success\":false,\"message\":\"不能删除管理员用户\"}");
                    return;
                }
            }
            
            int successCount = 0;
            int failCount = 0;
            
            for (Long userId : userIds) {
                try {
                    // 逻辑删除用户（将状态设为0）
                    boolean success = userService.updateUserStatus(userId, 0);
                    if (success) {
                        successCount++;
                    } else {
                        failCount++;
                    }
                } catch (Exception e) {
                    failCount++;
                }
            }
            
            if (failCount == 0) {
                out.print("{\"success\":true,\"message\":\"成功删除 " + successCount + " 个用户\"}");
            } else {
                out.print("{\"success\":true,\"message\":\"成功删除 " + successCount + " 个用户，失败 " + failCount + " 个\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\":false,\"message\":\"服务器错误：" + e.getMessage() + "\"}");
        } finally {
            out.flush();
            out.close();
        }
    }
}










